package cn.tedu.v3;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
/**
 * Version 3.0 多人聊天室   双向互通
 * 步骤1：找到start启动方法，增加线程【lambda表达式】控制读
 *    2:定义读写，统一在一起，读写功能，顺序按照定义排序！
 *    3.定义和功能分开，目的：增加可读性，保障逻辑顺序一致！
 *    4.读入功能增加到线程中
 */

public class Client {

    private Socket socket;
    private String ip;
    public Client() {
        try {
            socket = new Socket("127.0.0.1", 4545);
            ip=socket.getInetAddress().getHostAddress();
        }catch (NullPointerException e){
            System.out.println("友情提示：IP传入错误导致链接失败");
        }
        catch (UnknownHostException e) {
            System.out.println("友情提示：IP可能传入错误");
        }catch (ConnectException e){
            System.out.println("客户端链接失败：建议检查IP或者端口号");
        } catch (IOException e) {
            System.out.println("客户端链接服务器失败，提示：检查IP/端口");
        }
    }

    public void start() {

        PrintWriter pw=null;
//        BufferedReader br=null;//置空：赋值，关流
        try {
            //2.定义读入：客户端输入流，目的：代码可读性
            BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF8"));
            //1.定义写出:客户端输出流
           pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);

       //2.1 读入功能：存线程中
            new Thread(()->{
                try {

                    //2.2读入功能：①置空，不加，确定message一定读取数据
                    String message;
                    //②读取服务器发来的消息:读入一行不为空，一直有数据
                    //br.readLine()读取一行

                    while ((message = br.readLine()) != null) {
                        System.out.println("服务器端说："+message);
                    }
                    }catch (IOException e){
                    System.out.println("服务器端读入失败");
                }

            }).start();

            //1.1写出功能
         System.out.println(ip+"对服务器端说话：");
            Scanner input = new Scanner(System.in);
            while (true) {
                System.out.println("客户端请输入：");
                String say=input.nextLine();
                pw.println("客户端说:"+say);
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("客户端/服务器端编码集有问题！");
        } catch (IOException e) {
            System.out.println("客户端链接服务器端：IO流操作出现错误！");
        } finally {
            if (pw != null)
                pw.close();
        }
        }





    public static void main(String[] args) throws IOException {

        Client client = new Client();
        client.start();
    }
}
